<?php

namespace app\home\controller;

use app\common\controller\Home;
// 引用tp的基础控制器
use think\Controller;

use Qiniu\Auth;
use Qiniu\Config;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
class Qinie extends Home
{
    public function __construct(){
        // 手动继承父级
        parent::__construct();

        $this->access_key = Config('access_key');

        $this->secret_key = Config('secret_key');

        $this->domain = Config('domain');

        $this->bucket = Config('bucket');
    }
    public function qinie()
    {
        if(isset($_FILES) && isset($_FILES['favicon'])){
            $file = request()->file('favicon');
            if(!$file->isValid()){
                return '不合法文件';
            }
            $filePath = $file->getRealPath();
            // 获取文件扩展名
            $ext = substr($file->getInfo('name'), strrpos($file->getInfo('name'), '.'));
            // 新的文件名
            $key = md5(time().rand(1000,9999)) . $ext;
            // 构建鉴权对象
            $auth = new Auth($this->access_key, $this->secret_key);
            // 要上传的空间
            $token = $auth->uploadToken($this->bucket);
            // 初始化 UploadManager 对象并进行文件的上传
            $uploadMgr = new UploadManager();
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
            if ($err) {
                return '上传失败';
            } else {
                //返回图片的完整URL
                var_dump($ret);
                exit;
            }
        }
        return $this->fetch();
    }
    /**
     * 删除文件
     * @param string $filekey
     * @return int 1:删除成功 ，0:删除失败
     */
    public function deleteQiniuFile(){
        $file_key = $this->request->param('filekey');
        $auth = new Auth($this->access_key, $this->secret_key);
        $config = new Config();
        $bucketManager = new BucketManager($auth, $config);
        list($ret, $err) = $bucketManager->delete($this->bucket, $file_key);
        if ($err) {
            return 0;
        }else{
            return 1;
        }
    }

}